
package com.wallj.videolibrary.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextPaint;
import android.text.TextUtils;

import com.eyedog.library.utils.DensityUtils;

public class Text2BitmapUtils {

    public static Bitmap createBitmap(Context context, int width, int height, String text) {
        if (context == null || width <= 0 || height <= 0 || TextUtils.isEmpty(text)) {
            return null;
        }

        TextPaint textPaint = new TextPaint();
        textPaint.setColor(Color.WHITE);
        int textSize = DensityUtils.dp2px(context, 14);
        textPaint.setTextSize(textSize);
        textPaint.setFakeBoldText(true);
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        float distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
        float baseline = height / 2.0f + distance;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawText(text, 0, baseline, textPaint);
        return bitmap;
    }
}
